<?php 

/**
 * 店铺员工管理
 * @Author      jiating
 * @DateTime    2018-04-12
 */

namespace app\admin\controller;
use \think\Request;
use app\admin\model\Module;
use app\admin\model\Store;

class Operator extends Base{

	public function __construct() {
		parent::__construct();
		$this->model = model('Operator');
	}
	
	public function index() {
		return $this->fetch();
	}

    public function indexApi() {
        $request = Request::instance();
        $param = $request->param();

        $start = $param['start'];  //每页起始条数
        $length = $param['length'];  //每页条数

        $where = ['tenantId'=>session('TENANT_ID')];
        $member = session('member');

        if( $member['roleType'] == 2) {
            $where['storeId'] = $member['storeId'];
        }
        $sotres = Store::where('tenantId',session('TENANT_ID'))->select();
        $storeMap = [];
        foreach ($sotres as $v) {
            $storeMap[$v['id']] = $v['name'];
        }
        $list = $this->model->where($where)->where('roleType','neq',0)->where('id','neq',$member['id'])->limit($start,$length)->order("createDate DESC")->select();
        foreach ($list as $k => $l) {
            $list[$k]['storeName'] = $l['roleType'] == 2 ? $storeMap[$l['storeId']] : '-';
        }
        $count = $this->model->where($where)->where('roleType','neq',0)->where('id','neq',$member['id'])->count();

        $res = [
            'status' => '1',
            'draw' => $param['draw'],
            'data' => $list,
            'recordsFiltered' => $count,
            'recordsTotal' => $count
        ];
        return json($res);
    }

	public function add() {
		$list = model('store')->where(['tenantId'=>session('TENANT_ID')])->select();
		$this->assign('list',$list);

		$module = model('module')->where('isRoleSet','in','0,1')->where('isActive',1)->order('sorting')->select();  //说明：isRoleSet为0表示默认权限
		$this->assign('module',$module);

		return $this->fetch();
	}

	public function addPost() {
		$member = session('member');
		$post = input('post.');
        // return $post;

		if($post['pass_one'] != $post['pass_tow']) {
            return json(['code'=>'2','message'=>'两次密码不一致']);
			return $this->error('');
		}
		if($post['roleType'] == 2 && (!isset($post['storeId']) || empty($post['storeId']))) {
            return json(['code'=>'2','message'=>'请选择门店']);
		}

        if(!isset($post['moduleIds']) || empty($post['moduleIds'])) {
            return json(['code'=>'2','message'=>'请选择相关权限']);
        }

		$row = $this->model->where(['tenantId'=>$member['tenantId'],'loginName'=>$post['loginName']])->find();
		if($row) {
            return json(['code'=>'2','message'=>'账号重复，请重新设置']);
		}

        $moduleIds = json_decode($post['moduleIds'],true);
		if(is_array($moduleIds)){
            foreach ($moduleIds as $m) {
                $find = Module::where('id',$m)->find();
                if($find['typeId'] != '0') {
                    $moduleIds[] = $find['typeId'];
                }
            }
        }else{
            $find = Module::where('id',$moduleIds)->find();
            if($find['typeId'] != '0') {
                $moduleIds[] = $find['typeId'];
            }
        }

        $moduleIds = is_array($moduleIds) ? implode(',', $moduleIds) : $moduleIds;

        $data = [
        	'id' => get_uniqid_id(),
         	'name' => $post['name'],
        	'password' => md5($post['pass_tow']),
        	'phone' => $post['phone'],
        	'roleType' => $post['roleType'],
        	'tenantCode' => $member['tenantCode'],
        	'loginName' => $post['loginName'],
        	'moduleIds' => $moduleIds,
        	'createDate' => date('Y-m-d H:i:s',time()),
        	'updateDate' => date('Y-m-d H:i:s',time()),
        	'createOper' => $member['id'],
        	'updateOper' => $member['id'],
        	'storeId' => $post['storeId'] ? : 0,
        	'tenantId' => $member['tenantId']
        ];
        $add = $this->model->insert($data);
        if($add) {
            return json(['code'=>'1','message'=>'添加成功']);
        	return $this->redirect('index');
        } else {
            return json(['code'=>'2','message'=>'网络出错，请重试']);
        	return $this->error('网络出错，请重试');
        }
	}

	public function edit() {
		$id = $this->request->param('id');
		$row = $this->model->where(['id'=>$id])->find();

		if($row['tenantId'] != session('TENANT_ID')) {  //验证所修改的是否为同一店铺的员工
			return $this->error('只能修改本店铺的员工！');
		}

        $list = model('store')->where(['tenantId'=>session('TENANT_ID')])->select();
        $this->assign('list',$list);    

        $module = model('module')->where('isRoleSet','in','0,1')->where('isActive',1)->order('sorting')->select();  //说明：isRoleSet为0表示默认权限
		$this->assign('module',$module);
		$this->assign('row',$row);
		return $this->fetch();
	}


	public function editPost() {
		$post = input('post.');
        // return $post;
		if($post['pass_one'] != $post['pass_tow']) {
            return json(['code'=>'2','message'=>'两次密码不一致']);
			return $this->error('两次密码不一致');
		}

        if($post['roleType'] == 2 && (!isset($post['storeId']) || empty($post['storeId']))) {
            return json(['code'=>'2','message'=>'请选择门店']);
        }

        if(!isset($post['moduleIds']) || empty($post['moduleIds'])) {
            return json(['code'=>'2','message'=>'请选择相关权限']);
        }
        
        $moduleIds = json_decode($post['moduleIds'],true);
        if(is_array($moduleIds)){
            foreach ($moduleIds as $m) {
                $find = Module::where('id',$m)->find();
                if($find['typeId'] != '0') {
                    $moduleIds[] = $find['typeId'];
                }
            }
        }else{
            $find = Module::where('id',$moduleIds)->find();
            if($find['typeId'] != '0') {
                $moduleIds[] = $find['typeId'];
            }
        }

        $moduleIds = is_array($moduleIds) ? implode(',', $moduleIds) : $moduleIds;

		$data = [
        	'name' => $post['name'],
        	'phone' => $post['phone'],
            'storeId' => $post['storeId'],
            'roleType' => $post['roleType'],
        	'moduleIds' => $moduleIds,
        	'updateDate' => date('Y-m-d H:i:s',time()),
        	'updateOper' => session('TENANT_ID'),
        ];

        if(!empty($post['pass_one'])) {
        	$data['password'] = md5($post['pass_one']);
        }
        //return $data;
        $save = $this->model->where(['id'=>$post['id']])->update($data);
        if($save) {
            return json(['code'=>'1','message'=>'修改成功']);
        } else{
            return json(['code'=>'2','message'=>'网络出错，请重试']);
        }
	}


	public function delete() {
		$id = $this->request->param('id');
        // return $id;
        $where = ['id'=>$id,'tenantId'=>session('TENANT_ID')];

        if($this->model->where($where)->delete()) {
            return json(['code'=>'1','message'=>'修改成功']);
        } else {
        	return json(['code'=>'2','message'=>'网络出错，请重试']);
        }
	}


}